package org.jeecg.modules.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.util.HashSet;
import java.util.Set;
import java.util.TreeSet;

public class JsonUtils {
    public JsonUtils() {

    }


    public static String fixFormat(String jsonStr) {
        boolean flag1 = true;
        boolean flag2 = true;
        try {
            JSONObject jsonObject = JSON.parseObject(jsonStr);
        } catch (Exception e) {
            flag1 = false;
        }
        if (flag1) {
            return jsonStr;
        }
        try {
            JSONArray objects = JSON.parseArray(jsonStr);
            return jsonStr;
        } catch (Exception e) {
            flag2 = false;
        }
        if (flag2) {
            return jsonStr;
        }

        Set<String> set = new TreeSet<String>();
        String[] split = jsonStr.split("\\[|\\{|\\}|\\]|,|:");

        for (String s : split) {
            if (s.trim().length() > 0) {
                set.add(s.trim());

            }
        }
        Set<String> list = new HashSet<>();
        for (String s : set) {
            for (String k : set) {
                if (s.contains(k) && !s.equals(k)) {
                    list.add(k);
                }
            }
        }


        for (String s : set) {
            if (!list.contains(s) && s.length() >= 2)

                jsonStr = jsonStr.replaceAll(s, "\"" + s + "\"");

        }
        System.out.println(jsonStr);
        for (String s : list) {
            if (s.length() >= 2)
                jsonStr = jsonStr.replaceAll(s + ":", "\"" + s + "\":");

        }

        return jsonStr;
    }

    public static boolean isNumber(String jsonStr) {
        for (char c : jsonStr.toCharArray()) {
            if (!Character.isDigit(c)) {
                return false;
            }
        }

        return true;
    }

    public static void main(String[] args) {
        String s1 = "[{staffId:1657345145654784002, staffName:张三, staffInfo:{relateName:卸妆水, shareWay1:1, value2:1, value1:1, relateId:1661955112588337153, shareWay2:1, id:1673661003654057986, type:1}, workActor:1, shareWay:1, value:10}]";
        String s2 = "[{\"staffId\":\"1657345145654784002\", \"staffName\":\"张三\", \"staffInfo\":{\"relateName\":\"卸妆水\", \"shareWay1\":1, \"value2\":1, \"value1\":1, \"relateId\":\"1661955112588337153\", \"shareWay2\":1, \"id\":\"1673661003654057986\", \"type\":1}, \"workActor\":1, \"shareWay\":1, \"value\":10}]";
        String s = JsonUtils.fixFormat(s2);
        System.out.println(s);
        System.out.println(String.valueOf(null));

//        System.out.println(isNumber("1"));
//        System.out.println(isNumber("1.5"));
//        System.out.println(isNumber("153"));
//        System.out.println(isNumber("1 333"));

    }
}
